# -*- encoding: utf-8 -*-
##############################################################################
#
#    This program is free software: you can redistribute it and/or modify
#    it under the terms of the GNU Affero General Public License as published
#    by the Free Software Foundation, either version 3 of the License, or
#    (at your option) any later version.
#
#    This program is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.
#
#    You should have received a copy of the GNU Affero General Public License
#    along with this program.  If not, see http://www.gnu.org/licenses/.
#
##############################################################################

from datetime import timedelta
from datetime import date, datetime
from openerp.tools import DEFAULT_SERVER_DATETIME_FORMAT, DEFAULT_SERVER_DATE_FORMAT
from openerp import models, fields, api

class transportation_pricelist(models.Model):
    _name = "transportation.pricelist"
    _description = "Pricelist Version"

    @api.model
    def get_address_price(self,country_id,state_id,city,search_date=None):
        # todo
        print(search_date)
        if not search_date:
            today = datetime.today()
            search_date = today.strftime(DEFAULT_SERVER_DATE_FORMAT)
        pricelist = self.search([
            ('date_start','<=', search_date),
            ('date_end','>=', search_date),
            ],limit=1)
        price = pricelist.items_id.filtered(lambda record: record.city_id.name == city)
        return price and price.price or 0

    @api.one
    @api.depends('name_tpl','date_start', 'date_end')
    def compute_name(self):
        self.name = self.name_tpl.format(self.date_start,self.date_end)

    name = fields.Char(u'运输价格表', required=True, compute='compute_name', translate=True)
    name_tpl= fields.Char(u'名称模板', required=True, default=u'{0}-{1} 运输价格表')
    active = fields.Boolean(string=u'可用的',default=True)
    items_id = fields.One2many('transportation.pricelist.item', 'transportation_pricelist_id', u'价格明细',required=True,copy=True)
    date_start = fields.Date(string=u'开始日期')
    date_end = fields.Date(string=u'结束日期')

class transportation_pricelist_item(models.Model):
    _name = "transportation.pricelist.item"

    transportation_pricelist_id = fields.Many2one('transportation.pricelist', string=u'运输价格表',
        help="")
    country_id = fields.Many2one('res.country', string=u'国家',default=49) #中国
    country_state_id = fields.Many2one('res.country.state', string=u'省',)
    city_id = fields.Many2one('res.country.state.city', string=u'城市')
    price = fields.Float(u'价格', required=True)
